<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>说明书</title>
  <style>
    #image-container {
      display: flex;
      align-items: center;
    }

    .speaker {
      width: 100%;
      display: flex;
      justify-content: flex-end;
    }

    .page {
      display: flex;
      align-items: center;
      flex-direction: column;
      padding: 20px 20px 140px 20px;
    }

    .body {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      flex-direction: column;
    }

    .title {
      width: 100%;
      text-align: center;
      font-size: 60px;
      font-weight: bold;
    }

    .title1 {
      font-size: 40px;
      width: 70%;
      text-align: center;
      font-weight: 600;
      margin-top: 20px;
    }

    .btn {
      width: 100%;
      height: 90px;
      /* background: #eef0f1; */
      background: url('../../static/不带字.png') no-repeat;
      background-size: 100% 100%;
      border-radius: 8px;
      display: flex;
      justify-content: center;
      font-size: 40px;
      margin-top: 30px;
      font-weight: 400;
      color: #fff;
      align-items: center;
    }

    .content {
      width: 100%;
      padding: 0 30px;
      margin-top: 30px;
    }

    .content-img {
      width: 45px;
      height: 45px;
    }

    .content-flex {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .content-title {
      font-weight: 500;
      font-size: 45px;
      margin: 10px 0;
    }

    .content-info {
      font-size: 26px;
      margin: 10px 0;
      color: #7e7d7d;
    }

    .button {
      background: none;
    }

    #slider-container {
      width: calc(100% - 400px);
      text-align: center;
    }

    #slider {
      width: 100%;
      margin-top: 20px;
    }

    #value {
      font-size: 24px;
      margin-top: 20px;
    }

    .flex {
      width: 100%;
      position: fixed;
      bottom: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 42px;
      background: #fff;
      height: 140px;
    }
  </style>
</head>
<div id="image-container"></div>
<div class="speaker">
  <button onclick="handleSpeaker()">
    <img class="content-img" src="https://rb.biomedical-wh.com/prod-api//profile/bdm_img/broadcast.png" alt="" />
  </button>
</div>
<div class="flex">
  文字字号：
  <div id="slider-container">
    <input type="range" id="slider" min="32" max="60" value="45">
  </div>
</div>
<div>
  <button id="controll_tts">立即合成</button>
  <button id="download_pcm">下载pcm</button>
  <button id="download_wav">下载wav</button>
</div>

<div class="page">
  <div class="body">
    <div class="title" id="title">血塞通软胶囊说明书</div>
    <div class="title1">请仔细阅读说明书并在医师指导下使用</div>
    <div class="btn">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 活血化瘀,通脉活络</div>
    <div id="FWBcontent"></div>
  </div>
  <audio id="audioPlayer" controls style="display:none"></audio>

  <textarea id="textarea" style="display: none;" placeholder="请输入您要合成的文本">
    春江潮水连海平，海上明月共潮生。
</textarea>
  <div style="display:none">
    <div>语速([0-100])：<input id="speed" value="50" /></div>
    <div>音量([0-100])：<input id="volume" value="50" /></div>
    <div>音高([0-100])：<input id="pitch" value="50" /></div>
    <div>发音人：<input id="vcn" value="xiaoyan" /></div>
    <!-- x4_lingxiaolu_en -->
    <div>小语种(泰语)：<input id="tte" type="checkbox" /></div>
    <div>注意：发音人与语种会关联，小语种需要开通指定发音人</div>
  </div>

  <div id="result" style="display:none"></div>
</div>
<script src="../base64.js"></script>
<script src="../crypto-js.js"></script>
<script src="../../dist/index.umd.js"></script>
<script src="./index.js"></script>
<script>
  //滑块
  document.addEventListener('DOMContentLoaded', function () {
    var slider = document.getElementById('slider');
    var titleElement = document.getElementsByClassName('content-title');
    var infoElement = document.getElementsByClassName('content-info');
    var title = document.getElementById('title');
    var title1 = document.querySelector('.title1');

    // 监听input事件，当滑块值改变时更新显示值
    slider.addEventListener('input', function () {
      title.style.fontSize = parseInt(Number(slider.value) + 5) + 'px'
      title1.style.fontSize = slider.value - 5 + 'px'
      for (var i = 0; i < titleElement.length; i++) {
        titleElement[i].style.fontSize = slider.value + 'px';
        infoElement[i].style.fontSize = slider.value - 20 + 'px'

      }
    });
  });

  var hrefNum = window.location.href.split('=')[1]
  getContent(hrefNum)


  function handleSpeak1(msg) {
    // connectWebSocket();
    //  document.getElementById("textarea").value=msg;
    document.getElementById("controll_tts").click();
  }

  //获取页面所有文字
  function getTextByClassName(className) {
    const elements = document.getElementsByClassName(className);
    let allText = '';

    for (let i = 0; i < elements.length; i++) {
      let elementText = elements[i].textContent;
      allText += elementText + ' ';
    }

    allText = allText.trim();
    return allText;
  }
  function handleSpeaker(params) {
    const allText = getTextByClassName("body").replace(/\s/g, "");
    // handleSpeak(allText)
    handleSpeak2(allText);
  }

  // 获取整个页面的所有文字


  var speckConent = "";
  function handleSpeak2(msgData) {
    speckConent = msgData;
    connectWebSocket();
  };


  function handleSpeak(msg) {
    fetch("https://tsn.baidu.com/text2audio?tok=" + "24.ee8ce38fc0723287ab1b28f1a29e8b3a.2592000.1736909688.282335-116670895" +
      "&tex=" + msg +
      "&cuid=MQtX1eobGiuaFK4rbomQRDs8jHcvnms1&ctp=1&lan=zh&spd=5&pit=5&vol=5" +
      "&per=0" +
      "&aue=3")
      .then(response => response.blob()) // 将响应转换为Blob
      .then(blob => {
        // 创建一个URL表示此blob对象
        const blobUrl = URL.createObjectURL(blob);
        // 设置audio元素的src属性为新创建的URL
        document.getElementById('audioPlayer').src = blobUrl;
        // 播放音频
        document.getElementById('audioPlayer').play();
      });
  }

  var voiceType = "xiaoyu"
  function getContent(hrefNum) {
    fetch("http://121.41.46.17:8086/system/meidicineInfo/" + hrefNum)
      .then(response => response.json())
      .then(res => {
        var data = res.data
        console.log(data, 'data');
        voiceType = data.voiceType;
        //logo
        const images = data.logo.split(",");
        images.forEach(imageUrl => {
          const img = document.createElement('img');
          img.src = 'http://121.41.46.17:8088/prod-api' + imageUrl; // 设置img元素的src属性为图片的URL
          img.alt = ''; // 设置img元素的alt属性（可以根据需要为每个图片设置不同的alt）
          img.style.margin = '10px'; // 可选：为图片添加一些间距
          img.style.width = '120px'


          // 将img元素插入到页面上的指定容器中
          const imageContainer = document.getElementById('image-container');
          imageContainer.appendChild(img);
        });

        document.getElementById('title').innerHTML = data.medicineCnName;
        var htmlContent = ""
        for (let i = 0; i < data.medicineDetails.length; i++) {
          htmlContent += `
        <div class="content" >
          <div class="content-flex">
          <div class="content-title">【${data.medicineDetails[i].title}】</div>
            <button onclick="handleSpeak2('${data.medicineDetails[i].content}')">
              <img class="content-img" src="https://rb.biomedical-wh.com/prod-api//profile/bdm_img/broadcast.png" alt="" />
            </button>
          </div>
          <div class="content-info">${data.medicineDetails[i].content}</div>
        </div>`
        }
        document.getElementById('FWBcontent').innerHTML = htmlContent;

      });
  }


  /////
  const APPID = "b932cdd0";
  const API_SECRET = "NWUwYjczM2RkOGI3Y2QxOTQ2NTRmNzJj";
  const API_KEY = "1382eb84a2cda4a28cfd116e6b728ee6";

  let btnControl = document.getElementById("controll_tts");
  let btnStatus = "UNDEFINED"; // "UNDEFINED" "CONNECTING" "PLAY" "STOP"
  function changeBtnStatus(status) {
    // btnStatus = status;
    // if (status === "UNDEFINED") {
    //   btnControl.innerText = "立即合成";
    // } else if (status === "CONNECTING") {
    //   btnControl.innerText = "正在合成";
    // } else if (status === "PLAY") {
    //   btnControl.innerText = "停止播放";
    // } else if (status === "STOP") {
    //   btnControl.innerText = "重新播放";
    // }
  }

  const audioPlayer = new AudioPlayer("../../dist");
  audioPlayer.onPlay = () => {
    changeBtnStatus("PLAY");
  };
  audioPlayer.onStop = (audioDatas) => {
    console.log(audioDatas);
    btnStatus === "PLAY" && changeBtnStatus("STOP");
  };
  function getWebSocketUrl(apiKey, apiSecret) {
    var url = "wss://tts-api.xfyun.cn/v2/tts";
    var host = location.host;
    var date = new Date().toGMTString();
    var algorithm = "hmac-sha256";
    var headers = "host date request-line";
    var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2/tts HTTP/1.1`;
    var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    var signature = CryptoJS.enc.Base64.stringify(signatureSha);
    var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    var authorization = btoa(authorizationOrigin);
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
    return url;
  }
  function encodeText(text, type) {
    if (type === "unicode") {
      let buf = new ArrayBuffer(text.length * 4);
      let bufView = new Uint16Array(buf);
      for (let i = 0, strlen = text.length; i < strlen; i++) {
        bufView[i] = text.charCodeAt(i);
      }
      let binary = "";
      let bytes = new Uint8Array(buf);
      let len = bytes.byteLength;
      for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      return window.btoa(binary);
    } else {
      return Base64.encode(text);
    }
  }

  let ttsWS;
  function connectWebSocket() {
    const url = getWebSocketUrl(API_KEY, API_SECRET);
    if ("WebSocket" in window) {
      ttsWS = new WebSocket(url);
    } else if ("MozWebSocket" in window) {
      ttsWS = new MozWebSocket(url);
    } else {
      alert("浏览器不支持WebSocket");
      return;
    }
    changeBtnStatus("CONNECTING");

    ttsWS.onopen = (e) => {
      audioPlayer.start({
        autoPlay: true,
        sampleRate: 16000,
        resumePlayDuration: 1000
      });
      changeBtnStatus("PLAY");
      // var tte = document.getElementById("tte").checked ? "unicode" : "UTF8";
      var tte = "UTF8";
      var params = {
        common: {
          app_id: APPID,
        },
        business: {
          aue: "raw",
          auf: "audio/L16;rate=16000",
          vcn: voiceType,
          speed: 50,
          volume: 50,
          pitch: 50,
          bgs: 1,
          tte,
        },
        data: {
          status: 2,
          text: encodeText(speckConent, tte),
        },
      };
      ttsWS.send(JSON.stringify(params));
    };
    ttsWS.onmessage = (e) => {
      let jsonData = JSON.parse(e.data);
      // 合成失败
      if (jsonData.code !== 0) {
        console.error(jsonData);
        changeBtnStatus("UNDEFINED");
        return;
      }
      audioPlayer.postMessage({
        type: "base64",
        data: jsonData.data.audio,
        isLastData: jsonData.data.status === 2,
      });
      if (jsonData.code === 0 && jsonData.data.status === 2) {
        ttsWS.close();
      }
    };
    ttsWS.onerror = (e) => {
      console.error(e);
    };
    ttsWS.onclose = (e) => {
      // console.log(e);
    };
  };


</script>

</body>

</html>